package com.hwxm.ltim.util;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通道管理器
 * 管理所有在线用户的 WebSocket 连接
 */
@Slf4j
public class ChannelManager {

    /**
     * 存储用户ID与通道的映射关系
     * key: userId, value: Channel
     */
    private static final Map<Long, Channel> USER_CHANNELS = new ConcurrentHashMap<>();

    /**
     * 存储通道ID与用户ID的映射关系
     * key: channelId, value: userId
     */
    private static final Map<String, Long> CHANNEL_USERS = new ConcurrentHashMap<>();

    /**
     * 绑定用户与通道
     */
    public static void bindUserChannel(Long userId, Channel channel) {
        String channelId = channel.id().asLongText();
        USER_CHANNELS.put(userId, channel);
        CHANNEL_USERS.put(channelId, userId);
        log.info("用户 {} 绑定通道 {}", userId, channelId);
    }

    /**
     * 解绑用户与通道
     */
    public static void unbindUserChannel(Long userId) {
        Channel channel = USER_CHANNELS.remove(userId);
        if (channel != null) {
            String channelId = channel.id().asLongText();
            CHANNEL_USERS.remove(channelId);
            log.info("用户 {} 解绑通道 {}", userId, channelId);
        }
    }

    /**
     * 根据通道ID移除连接
     */
    public static void removeChannel(String channelId) {
        Long userId = CHANNEL_USERS.remove(channelId);
        if (userId != null) {
            USER_CHANNELS.remove(userId);
            log.info("移除通道 {}，用户 {}", channelId, userId);
        }
    }

    /**
     * 获取用户的通道
     */
    public static Channel getUserChannel(Long userId) {
        return USER_CHANNELS.get(userId);
    }

    /**
     * 根据通道ID获取用户ID
     */
    public static Long getUserIdByChannel(String channelId) {
        return CHANNEL_USERS.get(channelId);
    }

    /**
     * 判断用户是否在线
     */
    public static boolean isOnline(Long userId) {
        return USER_CHANNELS.containsKey(userId);
    }

    /**
     * 发送消息给指定用户
     */
    public static boolean sendToUser(Long userId, String message) {
        Channel channel = USER_CHANNELS.get(userId);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(new TextWebSocketFrame(message));
            return true;
        }
        return false;
    }

    /**
     * 获取在线用户数量
     */
    public static int getOnlineCount() {
        return USER_CHANNELS.size();
    }
}

